﻿using RoboSensors.Communicate;
using RoboSensors.Tools;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
///说明：Tcpservice用于接收重心数据、及交互发送
///31TcpClient用于发送script，暂无接收
///
///
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using UrPortCommunicate;
using UrScriptProgram;

namespace UrTransPayload
{
    public enum ScriptType
    {
        配重,
        回零关机,
        上移,
        初始位置
    }
    public class UrService
    {
        private String data = "";
        private TcpService m_TcpService;
        private UrClient30001 m_Client31 = new UrClient30001();
        private UrClient29999 m_Client29 = new UrClient29999();

        private string m_FloderPath = "C://medbotConfig";
        private String m_JsonPath { get; set; }

        public UrService()
        {
            m_JsonPath = m_FloderPath + "//config.json";
            CreateFloder(m_FloderPath);
        }
        public void Close()
        {
            m_TcpService.Close();
            m_Client31.Close();
        }
        #region 服务器端口操作函数
        public Action<List<String>> ScriptDataCallBack;
        public Action<String> PoPCallBack;
        public void OpenNewTcpService(string ip, string port)
        {
            m_TcpService = new TcpService(ip, port);
            m_TcpService.Open();
            m_TcpService.TcpServiceDataEvent += Service_TcpServiceDataEvent;
        }

        public void TcpServiceSend(string str)
        {
            m_TcpService.Add2SendLoop(str);
        }

        private void Service_TcpServiceDataEvent(object sender, string e)
        {
            if (e == "popToolDown")
            {
                PoPCallBack("请取下工具");
                return;
            }
            if (e == "popToolUp")
            {
                PoPCallBack("请安装工具");
                return;
            }
            data += e;
            if (data.Where(s => s == ' ').Count() == 4)
            {
                m_TcpService.Close();
                List<String> datalist = new List<string>();
                var dddd = data.Split(' ');
                foreach (var d in dddd)
                {
                    Console.WriteLine(d);
                    datalist.Add(d);
                }
                ScriptDataCallBack(datalist);
                data = "";
            }
        }

        #endregion

        #region 30001端口操作功能函数

        public void OpenNew31TcpClient(string ip, int port)
        {
            m_Client31.Open(ip, port);

        }


        public void SendUrScript(ScriptType type)
        {
            if(type==ScriptType.配重)
            {
                string command = UrTranspayload.GetScript();
                m_Client31.SendUrScript(command);
            }
            if(type==ScriptType.回零关机)
            {
                string command = UrGoHome.GetScript();
                m_Client31.SendUrScript(command);
            }
            if (type == ScriptType.上移)
            {
                string command = GoUp.GetScript();
                m_Client31.SendUrScript(command);
            }
            if (type == ScriptType.初始位置)
            {
                string command = InitPos.GetScript();
                m_Client31.SendUrScript(command);
            }

        }

        public void Close31TcpClient()
        {
            data = "";
            m_Client31.Close();
        }

        #endregion

        #region 29999端口操作功能函数
        public void OpenNew29TcpClient(string ip, int port=29999)
        {
            m_Client29.Open(ip, port);

        }

        public string Send29DashBoradCmd(DashCommand cmd, string str = "")
        {
            return m_Client29.SendCommand(cmd, str);
        }

        public void Close29TcpClient()
        {
            m_Client29.Close();
        }

        #endregion

        #region JSON相关操作
        public RobotCfg GetConfigFromJson(string path="")
        {
            if (path == "") path = m_JsonPath;
            string jsonstr="";
            StreamReader sr = new StreamReader(path, Encoding.Default);
            string content;
            while ((content = sr.ReadLine()) != null)
            {
                jsonstr += content;
            }
            var root=JsonHelper.FromJson<RobotCfg>(jsonstr);
            return root;

        }

        public void Write2ConfigJson(RobotCfg root, string path = "")
        {
            if (path == "") path = m_JsonPath;
            string FileName = path;
            CreateFile(path);
            var jsonstr=JsonHelper.ToJson(root);
            FileStream fs = new FileStream((FileName), FileMode.Open, FileAccess.ReadWrite);
            if (File.Exists(FileName))
            {
                fs.SetLength(0); //先清空文件
            }
            StreamWriter sw = new StreamWriter(fs);
            sw.Write(jsonstr);   //写入字符串
            sw.Close();
        }
        #endregion

        #region docker相关操作
        public String dockerid { get; set; }
        public String GetDockerID()
        {
            bool result = false;
            var cmdstr=RunCmd("docker ps -a");
            #region 
            //  Microsoft Windows[版本 10.0.19042.1348]
            //(c)Microsoft Corporation。保留所有权利。

            //F:\1 华南理工大学项目代码\UR\UrTransPayload\UrTransPayload\bin\Debug > docker ps
            //  CONTAINER ID IMAGE                   COMMAND CREATED       STATUS PORTS     NAMES
            //4249d323a5d2 medbot-slave - app:1.12   "bash"    4 weeks ago   Up About a minute             strange_dewdney

            //F:\1 华南理工大学项目代码\UR\UrTransPayload\UrTransPayload\bin\Debug > exit
            #endregion
            var cmdstrline =cmdstr.Split('\n');
            var goalline=cmdstrline.Where(s => s.Contains("medbot-slave")).ToList();
            if (goalline.Count != 0)
                dockerid = goalline.First().Split(' ')[0];
            else
                throw new Exception("can not get dockerid,please check：docker name should contain  medbot-slave");
            return dockerid;
        }
        public void PraseJson2Docker()
        {
            RunCmd(string.Format("docker cp {0} {1}:/opt/medbot/slave/config/",m_JsonPath, dockerid));
        }

        public void PraseJson2Windows()
        {
            RunCmd(string.Format("docker cp {0}:/opt/medbot/slave/config/config.json {1}", dockerid, m_JsonPath));
        }

        public void RestartDocker()
        {
            GetDockerID();
            RunCmd("docker restart " + dockerid,false);
        }

        private String RunCmd(string cmd,bool readOut=true)
        {
            try
            {
                using (Process myPro = new Process())
                {
                    myPro.StartInfo.FileName = "cmd.exe";
                    myPro.StartInfo.UseShellExecute = false;
                    myPro.StartInfo.RedirectStandardInput = true;
                    myPro.StartInfo.RedirectStandardOutput = true;
                    myPro.StartInfo.RedirectStandardError = true;
                    myPro.StartInfo.CreateNoWindow = true;
                    myPro.Start();
                    //如果调用程序路径中有空格时，cmd命令执行失败，可以用双引号括起来 ，在这里两个引号表示一个引号（转义）
                    //string str = string.Format(@"""{0}"" {1} {2}", cmdExe, cmdStr, "&exit");

                    myPro.StandardInput.WriteLine(cmd);
                    myPro.StandardInput.AutoFlush = true;
                    myPro.StandardInput.WriteLine("exit");
                    string output = "";
                    if(readOut==true)
                    {
                        output = myPro.StandardOutput.ReadToEnd();
                        myPro.WaitForExit();
                    }

                    return output;
                }
            }
            catch
            {
                return "";
            }
        }


        #endregion

        #region 关机

        public void ShutDown()
        {
            RunCmd("shutdown -s -t 0");
        }
        #endregion


        private void CreateFile(string path)
        {
            if(!System.IO.File.Exists(path))
            {
                using (System.IO.File.Create(path))
                {

                }
            }
        }

        private void CreateFloder(string path)
        {
            if (!System.IO.Directory.Exists(path))
            {
                System.IO.Directory.CreateDirectory(path);  
            }
        }

    }
}
